﻿using System;
using System.Text;
using System.Xml;
using System.Reflection;
using Portal.Api;
using Portal.Api.FeedProvider;

namespace Portal
{
  public partial class Rss : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      Type rssFeedProvider = null;
      string moduleType = null;
      string moduleRef = Request.QueryString["m"];
      if(!string.IsNullOrEmpty(moduleRef))
      {
        // Determine Module Type.
        moduleType = GetModuleType();

        // Retrieve the type of the Rss Feed Provider.
        if(!string.IsNullOrEmpty(moduleType))
        {
          rssFeedProvider = GetDataProvider(moduleType);
        }
      }

      Response.Clear();
      Response.ContentEncoding = Encoding.UTF8;

      // Add the Data of the provider.
      try
      {
        if (rssFeedProvider != null)
        {
          ModuleDocument doc = new ModuleDocument(moduleRef, moduleType);
          IFeedDataProvider provider = Activator.CreateInstance(rssFeedProvider) as IFeedDataProvider;
          if (provider != null)
            provider.ProvideFeed(Request, Response, doc);
        }
        else
          Response.StatusCode = 404;  // Not found.
      }
      catch (System.Exception)
      {
        Response.StatusCode = 500;    // Internal Server Error.
      }

      Response.End();
    }

    /// <summary>
    /// Returns the type of the module to the requested feed.
    /// </summary>
    /// <returns>The Type as string, null if the module doesn't exist</returns>
    private string GetModuleType()
    {
      if (!string.IsNullOrEmpty(Request.QueryString["m"]))
      {
        PortalDefinition portDef = PortalDefinition.Load();
        var module = portDef.GetModule(Request.QueryString["m"]);
        if(module != null)
        {
          return module.type;
        }
      }
      return null;
    }

    /// <summary>
    /// Returns the type of the requested Rss-Feed DataProvider.
    /// </summary>
    /// <param name="moduleType"></param>
    /// <returns></returns>
    private Type GetDataProvider(string moduleType)
    {
      if (!string.IsNullOrEmpty(Request.QueryString["t"]))
      {
        string rssType = Request.QueryString["t"];

        Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
        foreach (Assembly asm in asms)
        {
          foreach (Type candidate in asm.GetTypes())
          {
            foreach (Attribute attr in candidate.GetCustomAttributes(typeof(FeedDataProviderAttribute), true))
            {
              FeedDataProviderAttribute dataProviderAttr = attr as FeedDataProviderAttribute;
              if ((rssType == dataProviderAttr.Identifier) && (moduleType == dataProviderAttr.ModuleType))
              {
                return candidate;
              }
            }
          }
        }
      }
      return null;
    }
  }
}